package com.example.math;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SecondScreenListArrayAdapter extends
		ArrayAdapter<SecondScreenListClass> {

	private static final String tag = "itemArrayAdapter";
	private static final String ASSETS_DIR = "images/";
	private Context context;

	private ImageView itemIcon;
	private TextView itemName;
	private List<SecondScreenListClass> items = new ArrayList<SecondScreenListClass>();

	public SecondScreenListArrayAdapter(Context context,
			int textViewResourceId, List<SecondScreenListClass> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.items = objects;
	}

	public int getCount() {
		return this.items.size();
	}

	public SecondScreenListClass getItem(int index) {
		return this.items.get(index);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		if (row == null) {
			// ROW INFLATION
			Log.d(tag, "Starting XML Row Inflation ... ");
			LayoutInflater inflater = (LayoutInflater) this.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.listitem, parent, false);
			Log.d(tag, "Successfully completed XML Row Inflation!");
		}

		// Get item
		SecondScreenListClass item = getItem(position);
		itemIcon = (ImageView) row.findViewById(R.id.item_icon);
		itemName = (TextView) row.findViewById(R.id.item_name);

		itemName.setText(item.name);
		if (item.resourceId == null || item.resourceId.trim().length() == 0) {
			itemIcon.setImageBitmap(null);

		} else {
			String imgFilePath = ASSETS_DIR + item.resourceId;
			try {
				Bitmap bitmap = BitmapFactory.decodeStream(this.context
						.getResources().getAssets().open(imgFilePath));
				itemIcon.setImageBitmap(bitmap);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return row;
	}

}
